<template>
  <div>
    <div>组合曲线CurvePath拼接曲线</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  let scene: any = null;
  let camera: any = null;
  let render: any = null;
  onMounted(() => {
    init();
  });

  function init() {
    scene = new THREE.Scene();
    const width = 500;
    const height = 300;
    camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(-100, 300, 300);
    camera.lookAt(scene.position);
    render = new THREE.WebGLRenderer();
    render.setSize(width, height);
    webgl.value.appendChild(render.domElement);
    new OrbitControls(camera, render.domElement);
    const amLight = new THREE.AmbientLight(0xffffff);
    scene.add(amLight);
    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    const R = 80; //圆弧半径
    const H = 200; //直线部分高度
    // 直线1
    const line1 = new THREE.LineCurve(new THREE.Vector2(R, H), new THREE.Vector2(R, 0));
    // 圆弧
    const arc = new THREE.ArcCurve(0, 0, R, 0, Math.PI, true);
    // 直线2
    const line2 = new THREE.LineCurve(new THREE.Vector2(-R, 0), new THREE.Vector2(-R, H));
    // CurvePath创建一个组合曲线对象
    const CurvePath = new THREE.CurvePath();
    //line1, arc, line2拼接出来一个U型轮廓曲线，注意顺序
    CurvePath.curves.push(line1, arc, line2);
    // 执行.getPoints()，直线部分不会像曲线返回中间多余点，只需要起始点即可。
    // const pointsArr = CurvePath.getPoints(16) as THREE.Vector2[]; //曲线上获取点
    const pointsArr = CurvePath.getSpacedPoints(160) as THREE.Vector2[]; //圆弧不够光滑
    const geometry = new THREE.BufferGeometry();
    geometry.setFromPoints(pointsArr); //读取坐标数据赋值给几何体顶点

    // 可视化curve.getPoints从曲线上获取的点坐标
    const material2 = new THREE.LineBasicMaterial({
      color: 0xff00ff,
    });
    //点模型对象
    const points = new THREE.Line(geometry, material2);
    scene.add(points);

    renderFun();
  }
  function renderFun() {
    render.render(scene, camera);
    requestAnimationFrame(renderFun);
  }
</script>
<style lang=""></style>
